import {defineStore} from 'pinia'
import { RouteLocationNormalized, RouteRecordName } from 'vue-router'
import router from "@/router"

interface thistype{
    routelist:Array<RouteLocationNormalized>,
    guhuakey:string,
    activeName:RouteRecordName | null | undefined|string,
    guhua:RouteLocationNormalized | null,
}

export const useMyRouter = defineStore('useMyRouter', {
    state: () :thistype=> {
        return {
            routelist: [],    // 缓存的路由列表
            guhuakey: "Workflat",   // 固化的标签
            guhua: null,   // 固化的路由
            activeName: "",  // 当前激活的路由
        }
    },
    actions: {
        // 添加到缓存列表
        huancun(luyou: RouteLocationNormalized) {
            console.log(luyou, "是个什么东西")
            const jieguo = this.routelist.find((el: any) => el.name === luyou.name)
            if (!jieguo) {
                this.routelist.push(luyou)
            }
            this.activeName = luyou.name
        },
        // 从缓存列表里移除
        yichu(namelist: Array<string>) {
            for (let i = 0; i < namelist.length; i++) {
                const index = this.routelist.findIndex(el => el.name === namelist[i])
                if (index > -1) {
                    this.routelist.splice(index, 1)
                }
            }
            console.log(this.routelist, this.routelist.length, "现在的缓存情况")
            this.redirectitem()
        },
        // 清空缓存列表，除了固化的，其他的都清空
        qingkong() {
            this.routelist = []
            this.redirectitem()
        },
        // 移除顶部标签后，重新激活一个页面
        redirectitem() {
            console.log(this.routelist, this.routelist.length,this.activeName, "现在的缓存情况2")
            const jieguo = this.routelist.find(el => el.name === this.activeName)
            console.log(jieguo,"结果是什么")
            // 如果当前激活的页面不存在，就切换激活，
            if (!jieguo) {
                if(this.routelist.length > 0) {
                    router.push({ name: this.routelist[0].name })
                }else{
                    router.push({name:this.guhuakey})
                }
            }
        },
    },
    // pinia持久化
    // persist: {
    //     key: 'myrouter',    // 存储的key
    //     storage: window.sessionStorage, // 存储位置
    // },
    persist:false,
})
